import React, { useState } from 'react';
import { DataTable, BarChart, LineChart, Badge, type TableColumn } from "@repo/ui";
import styles from './DashboardPage.module.css';

interface Topic {
  id: string;
  name: string;
  description: string;
  count: number;
  status: 'active' | 'inactive' | 'pending';
  iconColor: 'blue' | 'green' | 'purple' | 'orange' | 'red';
  lastUpdated: string;
}

interface TopicData {
  id: string;
  name: string;
  description: string;
  chartData: any[];
  tableData: any[];
}

const DashboardPage: React.FC = () => {
  const [selectedTopicId, setSelectedTopicId] = useState<string>('1');
  const [searchTerm, setSearchTerm] = useState('');

  // 模拟话题数据
  const topics: Topic[] = [
    {
      id: '1',
      name: '用户增长分析',
      description: '用户注册和活跃度趋势',
      count: 1234,
      status: 'active',
      iconColor: 'blue',
      lastUpdated: '2小时前'
    },
    {
      id: '2',
      name: '销售业绩统计',
      description: '月度销售数据和转化率',
      count: 856,
      status: 'active',
      iconColor: 'green',
      lastUpdated: '1小时前'
    },
    {
      id: '3',
      name: '产品使用情况',
      description: '功能使用频率和用户反馈',
      count: 432,
      status: 'pending',
      iconColor: 'purple',
      lastUpdated: '30分钟前'
    },
    {
      id: '4',
      name: '系统性能监控',
      description: '服务器状态和响应时间',
      count: 89,
      status: 'active',
      iconColor: 'orange',
      lastUpdated: '15分钟前'
    },
    {
      id: '5',
      name: '客户服务质量',
      description: '客服响应时间和满意度',
      count: 267,
      status: 'inactive',
      iconColor: 'red',
      lastUpdated: '4小时前'
    }
  ];

  // 模拟话题详情数据
  const topicDetails: Record<string, TopicData> = {
    '1': {
      id: '1',
      name: '用户增长分析',
      description: '用户注册和活跃度趋势分析，包含新用户注册量、日活跃用户数、月活跃用户数等关键指标',
      chartData: [
        { name: '01-11', value: 278 },
        { name: '01-12', value: 156 },
        { name: '01-13', value: 312 },
        { name: '01-14', value: 189 },
        { name: '01-15', value: 245 },
        { name: '01-16', value: 298 },
        { name: '01-17', value: 334 }
      ],
      tableData: [
        { id: 1, date: '2024-01-15', newUsers: 245, activeUsers: 1892, retention: '78%', source: '自然搜索' },
        { id: 2, date: '2024-01-14', newUsers: 189, activeUsers: 1756, retention: '82%', source: '社交媒体' },
        { id: 3, date: '2024-01-13', newUsers: 312, activeUsers: 2103, retention: '75%', source: '广告投放' },
        { id: 4, date: '2024-01-12', newUsers: 156, activeUsers: 1634, retention: '79%', source: '推荐链接' },
        { id: 5, date: '2024-01-11', newUsers: 278, activeUsers: 1987, retention: '81%', source: '直接访问' }
      ]
    },
    '2': {
      id: '2',
      name: '销售业绩统计',
      description: '销售团队业绩数据，包含订单量、销售额、转化率等核心业务指标',
      chartData: [
        { name: '张三', value: 45 },
        { name: '李四', value: 38 },
        { name: '王五', value: 52 },
        { name: '赵六', value: 29 },
        { name: '钱七', value: 41 }
      ],
      tableData: [
        { id: 1, salesperson: '张三', orders: 45, revenue: '¥125,600', conversion: '12.5%', region: '华东' },
        { id: 2, salesperson: '李四', orders: 38, revenue: '¥98,400', conversion: '10.8%', region: '华北' },
        { id: 3, salesperson: '王五', orders: 52, revenue: '¥156,800', conversion: '15.2%', region: '华南' },
        { id: 4, salesperson: '赵六', orders: 29, revenue: '¥78,900', conversion: '9.1%', region: '西南' },
        { id: 5, salesperson: '钱七', orders: 41, revenue: '¥112,300', conversion: '11.7%', region: '华中' }
      ]
    },
    '3': {
      id: '3',
      name: '产品使用情况',
      description: '产品功能使用统计和用户行为分析，帮助优化产品体验',
      chartData: [
        { name: '用户管理', value: 2456 },
        { name: '数据分析', value: 1834 },
        { name: '报表生成', value: 1245 },
        { name: '系统设置', value: 678 },
        { name: '消息通知', value: 3421 }
      ],
      tableData: [
        { id: 1, feature: '用户管理', usage: 2456, users: 892, satisfaction: '4.2', trend: '+8%' },
        { id: 2, feature: '数据分析', usage: 1834, users: 567, satisfaction: '4.5', trend: '+12%' },
        { id: 3, feature: '报表生成', usage: 1245, users: 423, satisfaction: '3.8', trend: '-2%' },
        { id: 4, feature: '系统设置', usage: 678, users: 234, satisfaction: '4.1', trend: '+5%' },
        { id: 5, feature: '消息通知', usage: 3421, users: 1123, satisfaction: '4.3', trend: '+15%' }
      ]
    }
  };

  const filteredTopics = topics.filter(topic =>
    topic.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    topic.description.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const selectedTopic = topicDetails[selectedTopicId];

  // 表格列配置
  const getTableColumns = (topicId: string): TableColumn[] => {
    switch (topicId) {
      case '1':
        return [
          { key: 'date', title: '日期', dataIndex: 'date' },
          { key: 'newUsers', title: '新用户', dataIndex: 'newUsers', align: 'right' },
          { key: 'activeUsers', title: '活跃用户', dataIndex: 'activeUsers', align: 'right' },
          { key: 'retention', title: '留存率', dataIndex: 'retention', align: 'center' },
          { key: 'source', title: '来源', dataIndex: 'source' }
        ];
      case '2':
        return [
          { key: 'salesperson', title: '销售员', dataIndex: 'salesperson' },
          { key: 'orders', title: '订单数', dataIndex: 'orders', align: 'right' },
          { key: 'revenue', title: '销售额', dataIndex: 'revenue', align: 'right' },
          { key: 'conversion', title: '转化率', dataIndex: 'conversion', align: 'center' },
          { key: 'region', title: '地区', dataIndex: 'region' }
        ];
      case '3':
        return [
          { key: 'feature', title: '功能', dataIndex: 'feature' },
          { key: 'usage', title: '使用次数', dataIndex: 'usage', align: 'right' },
          { key: 'users', title: '用户数', dataIndex: 'users', align: 'right' },
          { key: 'satisfaction', title: '满意度', dataIndex: 'satisfaction', align: 'center' },
          { 
            key: 'trend', 
            title: '趋势', 
            dataIndex: 'trend', 
            align: 'center',
            render: (value: string) => (
              <span style={{ 
                color: value.startsWith('+') ? '#10b981' : '#ef4444',
                fontWeight: 500 
              }}>
                {value}
              </span>
            )
          }
        ];
      default:
        return [];
    }
  };

  const getStatusBadge = (status: Topic['status']) => {
    const statusConfig = {
      active: { 
        text: '活跃', 
        variant: 'success' as const,
        icon: (
          <svg width="8" height="8" viewBox="0 0 16 16" fill="currentColor">
            <path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.75.75 0 0 1 1.06-1.06L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"/>
          </svg>
        )
      },
      inactive: { 
        text: '停用', 
        variant: 'destructive' as const,
        icon: (
          <svg width="8" height="8" viewBox="0 0 16 16" fill="currentColor">
            <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.75.75 0 1 1 1.06 1.06L9.06 8l3.22 3.22a.75.75 0 1 1-1.06 1.06L8 9.06l-3.22 3.22a.75.75 0 0 1-1.06-1.06L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"/>
          </svg>
        )
      },
      pending: { 
        text: '待处理', 
        variant: 'warning' as const,
        icon: (
          <svg width="8" height="8" viewBox="0 0 16 16" fill="currentColor">
            <path d="M8 16A8 8 0 1 1 8 0a8 8 0 0 1 0 16ZM8 4a.75.75 0 0 0-.75.75v3.5a.75.75 0 0 0 1.5 0v-3.5A.75.75 0 0 0 8 4Zm0 8a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z"/>
          </svg>
        )
      }
    };
    
    const config = statusConfig[status];
    return (
      <Badge 
        variant={config.variant}
        size="sm"
        icon={config.icon}
        iconPosition="left"
      >
        {config.text}
      </Badge>
    );
  };

  return (
    <div className={styles.container}>
      {/* 左侧边栏 */}
      <div className={styles.sidebar}>
        <div className={styles.sidebarHeader}>
          <h2 className={styles.sidebarTitle}>话题列表</h2>
          <div className={styles.searchBox}>
            <svg className={styles.searchIcon} fill="currentColor" viewBox="0 0 20 20">
              <path fillRule="evenodd" d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z" clipRule="evenodd" />
            </svg>
            <input
              type="text"
              placeholder="搜索话题..."
              className={styles.searchInput}
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
            />
          </div>
        </div>
        
        <div className={styles.topicList}>
          {filteredTopics.map((topic) => (
            <button
              key={topic.id}
              className={`${styles.topicItem} ${selectedTopicId === topic.id ? styles.active : ''}`}
              onClick={() => setSelectedTopicId(topic.id)}
            >
              <div className={`${styles.topicIcon} ${styles[`topicIcon${topic.iconColor.charAt(0).toUpperCase() + topic.iconColor.slice(1)}`]}`}>
                {topic.name.charAt(0)}
              </div>
              <div className={styles.topicContent}>
                <div className={styles.topicName}>{topic.name}</div>
                <div className={styles.topicMeta}>
                  <Badge 
                    variant="secondary" 
                    size="sm"
                  >
                    {topic.count}
                  </Badge>
                  <span>•</span>
                  <span>{topic.lastUpdated}</span>
                  {getStatusBadge(topic.status)}
                </div>
              </div>
            </button>
          ))}
        </div>
      </div>

      {/* 右侧主内容 */}
      <div className={styles.mainContent}>
        {selectedTopic ? (
          <>
            <div className={styles.contentHeader}>
              <h1 className={styles.contentTitle}>{selectedTopic.name}</h1>
              <p className={styles.contentSubtitle}>{selectedTopic.description}</p>
            </div>
            
            <div className={styles.contentBody}>
              {/* 图表区域 */}
              <div style={{ marginBottom: '24px' }}>
                {selectedTopicId === '1' ? (
                  <LineChart
                    title="用户增长趋势"
                    subtitle="每日新用户注册数量变化"
                    data={selectedTopic.chartData}
                    color="#3b82f6"
                    showDots={true}
                    showGrid={true}
                  />
                ) : selectedTopicId === '2' ? (
                  <BarChart
                    title="销售业绩对比"
                    subtitle="各销售员订单数量统计"
                    data={selectedTopic.chartData}
                    color="#10b981"
                    showValues={true}
                  />
                ) : (
                  <BarChart
                    title="功能使用统计"
                    subtitle="各功能模块使用次数对比"
                    data={selectedTopic.chartData}
                    color="#8b5cf6"
                    horizontal={true}
                    showValues={true}
                  />
                )}
              </div>

              {/* 表格区域 */}
              <div>
                <DataTable
                  columns={getTableColumns(selectedTopicId)}
                  data={selectedTopic.tableData}
                  pagination={true}
                  pageSize={5}
                />
              </div>
            </div>
          </>
        ) : (
          <div className={styles.emptyState}>
            <svg className={styles.emptyIcon} fill="currentColor" viewBox="0 0 20 20">
              <path fillRule="evenodd" d="M3 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1z" clipRule="evenodd" />
            </svg>
            <div className={styles.emptyTitle}>请选择一个话题</div>
            <div className={styles.emptyDescription}>从左侧列表中选择一个话题来查看详细数据</div>
          </div>
        )}
      </div>
    </div>
  );
};

export default DashboardPage;
